package com.rattsoftware.client.views;

import java.util.ArrayList;
import java.util.List;

import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SortDir;
import com.extjs.gxt.ui.client.data.BasePagingLoadConfig;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.rattsoftware.client.AppMessages;
import com.rattsoftware.client.Refreshable;
import com.rattsoftware.client.RefreshableEvent;
import com.rattsoftware.client.controllers.DepartmentController;
import com.rattsoftware.client.events.AppEvents;
import com.rattsoftware.client.model.DepartmentSummary;
import com.rattsoftware.client.model.FacultySummary;
import com.rattsoftware.client.util.ProgressIndicator;
import com.rattsoftware.client.widgets.RemoteStoreFilterField;
import com.rattsoftware.client.widgets.SearchPagingToolBar;
import com.rattsoftware.server.admin.model.exceptions.RattsParsingException;

public class DepartmentView extends View implements Refreshable {

	final AppMessages appMessages = GWT.create(AppMessages.class);
	public static final int PAGE_SIZE = 10;

	private Window window;

	private Grid<DepartmentSummary> grid;
	private ColumnModel cm;
	SearchPagingToolBar<DepartmentSummary> toolBar;
	private PagingLoader<PagingLoadResult<DepartmentSummary>> loader;

	private List<DepartmentSummary> allDepartmentSummaries = new ArrayList<DepartmentSummary>();
	private ToolBar toolBarPanel;
	private ListStore<DepartmentSummary> store;
	private Button editButton, deleteButton;
	private FacultySummary facultySummary;
	
	public DepartmentView(Controller controller) {
		super(controller);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void handleEvent(AppEvent event) {
		GWT.log("DepartmentView : handleEvent");
		if (event.getType() == AppEvents.ViewDepartments) {
			facultySummary = event.getData();
			createUI("Registered Departments Under (" + facultySummary.getFacultyName() + ")");
		}
	}
	
	@Override
	protected void initialize() {

		GWT.log("DepartmentView : initialize");
		ProgressIndicator.showProgressBar();

		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
		configs.add(new ColumnConfig("departmentId", appMessages.id(), 20));
		configs.add(new ColumnConfig("departmentName", appMessages
				.departmentName(), 200));
		configs.add(new ColumnConfig("departmentHead", appMessages
				.departmentHead(), 250));
		configs.add(new ColumnConfig("noOfCourses", appMessages
				.noOfCourses(), 100));
		configs.add(new ColumnConfig("departmentDescription", appMessages
				.departmentDescription(), 250));

		cm = new ColumnModel(configs);
		cm.setHidden(0, true); // hide ID column

		toolBar = new SearchPagingToolBar<DepartmentSummary>(PAGE_SIZE);
		
		loader = new BasePagingLoader<PagingLoadResult<DepartmentSummary>>(
				new RpcProxy<PagingLoadResult<DepartmentSummary>>() {
					@Override
					public void load(
							Object loadConfig,
							final AsyncCallback<PagingLoadResult<DepartmentSummary>> callback) {
						ProgressIndicator.showProgressBar();
						final PagingLoadConfig pagingLoadConfig = (PagingLoadConfig) loadConfig;
						if (pagingLoadConfig.getSortField() == null
								|| pagingLoadConfig.getSortField().trim()
										.equals("")) {
							pagingLoadConfig.setSortField("name");
							pagingLoadConfig.setSortDir(SortDir.ASC);
						}
						pagingLoadConfig.set(RemoteStoreFilterField.PARM_FIELD,
								"name");
						pagingLoadConfig.set(RemoteStoreFilterField.PARM_QUERY,
								toolBar.getSearchFilterValue());
						GWT.log("DepartmentView RpcProxy:load loadConfig pageSize="
								+ pagingLoadConfig.getLimit() + " sortField="
								+ pagingLoadConfig.getSortField() + " filter="
								+ toolBar.getSearchFilterValue());
						Scheduler.get().scheduleDeferred(
								new ScheduledCommand() {
									@Override
									public void execute() {
										final DepartmentController controller = (DepartmentController) DepartmentView.this
												.getController();
										try {
											controller.getDepartments(pagingLoadConfig, callback);
										} catch (RattsParsingException e) {
											e.printStackTrace();
										}
									}
								});
					}
				});

		loader.setRemoteSort(true);
		toolBar.bind(loader);

		store = new ListStore<DepartmentSummary>(loader);
		grid = new Grid<DepartmentSummary>(store, cm);
		grid.setAutoExpandColumn("departmentDescription");
		grid.setAutoExpandMax(10000);
		grid.setStripeRows(true);
		grid.setHeight(300);
		grid.setBorders(true);

		// Edit
		editButton = new Button(appMessages.editDepartment());
		editButton.setIcon(IconHelper.createStyle("edit"));
		editButton.addListener(Events.Select, new Listener<ButtonEvent>() {
			@Override
			public void handleEvent(ButtonEvent be) {
				editDepartment();
			}
		});

		// delete
		deleteButton = new Button(appMessages.deleteDepartment());
		deleteButton.setIcon(IconHelper.createStyle("delete"));
		deleteButton.addListener(Events.Select, new Listener<ButtonEvent>() {
			@Override
			public void handleEvent(ButtonEvent be) {
				//deleteCourseUnit();
			}
		});

		toolBarPanel = new ToolBar();
		toolBarPanel.setSpacing(10);
		toolBarPanel.add(editButton);
		toolBarPanel.add(deleteButton);

		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			@Override
			public void execute() {
				// load the first set of data
				PagingLoadConfig config = new BasePagingLoadConfig(0, PAGE_SIZE);
				loader.load(config);
			}
		});
	}
	
	private void createUI(String title) {
		window = new Window();
		window.setHeading(title);
		window.setModal(true);
		window.setPlain(true);
		window.setMaximizable(false);
		window.setDraggable(true);
		window.setResizable(false);
		window.setSize(1200, 495);
		window.setScrollMode(Scroll.AUTOY);
		window.setLayout(new FitLayout());

		ProgressIndicator.showProgressBar();
		window.setTopComponent(toolBarPanel);
		window.add(grid);
		window.setBottomComponent(toolBar);
		ProgressIndicator.hideProgressBar();
		window.show();
	}
	
	private void editDepartment() {
		final DepartmentSummary summary = grid.getSelectionModel()
				.getSelectedItem();
		if (summary != null) {
			ProgressIndicator.showProgressBar();
			Scheduler.get().scheduleDeferred(new ScheduledCommand() {
				@Override
				public void execute() {
					DepartmentController controller = (DepartmentController) getController();
					controller.forwardToEditDepartmentController(summary, facultySummary);
				}
			});
			ProgressIndicator.hideProgressBar();
		} else {
			MessageBox.alert(appMessages.listOfFaculties(), appMessages
					.departmentNotSelected(), null);
		}
	}


	@Override
	public void refresh(RefreshableEvent event) {
		GWT.log("Refreshing...");
		if (event.getEventType() == RefreshableEvent.Type.DELETE_DEPARTMENT) {
			ListStore<DepartmentSummary> store = grid.getStore();
			DepartmentSummary summary = event.getData();
			if (summary != null) {
				store.remove(summary);
			}
		}
		if (event.getEventType() == RefreshableEvent.Type.REFRESH_DEPARTMENT_LIST) {
			toolBar.refresh();
		}
	}

	public void setAllDepartmentSummaries(List<DepartmentSummary> allDepartmentSummaries) {
		this.allDepartmentSummaries = allDepartmentSummaries;
	}

	public List<DepartmentSummary> getAllDepartmentSummaries() {
		return allDepartmentSummaries;
	}
}
